<template>
  <div class="mainControl">
    <VonCrumbs title="数据管理"></VonCrumbs>
    <div class="widget">
      <VonSelect v-model="selectType" width="150px" :options="searchItem" @change="changeSearchType"></VonSelect>
      <VonInput v-model="searchCondition" width="260px" placeholder="搜索"
        v-if="selectType == 'workStationId' || selectType == 'material' || selectType == 'tmpBarCode' || selectType == 'worker'">
      </VonInput>
      <VonDatePicker start_placeholder="开始日期" end_placeholder="结束日期" width="300px" v-model="createDate"
        v-if="selectType == 'dateRange'" />
      <!--       <VonDoubleInput start_placeholder="开始序号" end_placeholder="结束序号" width="150px" v-model="searchConditionRange"
                v-if="selectType=='tmpBarCodeRange' || selectType=='productBarCodeRange'" @change="searchRangeDataList"/>   -->
      <div v-if="selectType == 'tmpBarCodeRange' || selectType == 'productBarCodeRange'" class="range-header">
        <div class="range">
          <VonInput v-model="searchCondition_Start" width="150px" placeholder="开始序号"></VonInput>
          <span class="rangeTag">--</span>
          <VonInput v-model="searchCondition_End" width="150px" placeholder="结束序号"></VonInput>
        </div>
      </div>
      <el-button v-if="searchButtonFlag" type="primary" class="addButton" size="small" @click.stop="searchDataList()">
        查询
        <i class="el-icon-search el-icon--right"></i>
      </el-button>
      <el-button type="primary" class="addButton" size="small" @click.stop="exportData()">
        导出
        <i class="el-icon-upload el-icon--right"></i>
      </el-button>
    </div>
    <div class="tableContent">
      <VonTable height="672px" :column="column" :tableData="tableData" :showPagination="true"
        @getDrawerData="getDrawerData" selection @selectionChange="selectionChange" :total="totalCount"
        @handleCurrentChange="handleCurrentChange" @handleSizeChange="handleSizeChange">
        <template slot="num">
          <el-table-column label="序号" align="center" width="100px">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <el-table-column slot="operation" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" style="color: #1890ff" @click.stop="hangup(scope.row)">
              挂起
            </el-button>
            <el-button type="text" size="small" style="color: #1890ff" @click.stop="del(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </VonTable>
    </div>
    <VonDialog @commitResult="commitResult_Bad" @cancelResult="cancelResult_Bad" :isShow_Popup="isShow_Popup_Bad"
      :isShowCancelButton="false" successText="确定" cancelText="" title="注意" :isHasCloseBtu="false">
      <div slot="content">
        <div class="warningBox">
          <div style="text-align: center">
            <img src="../../assets/workStation/warningBox.png" alt="" />
            <div class="title_warning">挂起</div>
          </div>
        </div>
      </div>
    </VonDialog>
    <VonDialog @commitResult="commitResult_tightComplete" @cancelResult="cancelResult_tightComplete"
      :isShow_Popup="isShow_Popup_tightComplete" :isShowCancelButton="false" successText="确定" cancelText="" title="注意">
      <div slot="content">
        <div class="warningBox">
          <div style="text-align: center">
            <img src="../../assets/workStation/tightComplete.png" alt="" />
            <div class="title_warning">删除</div>
          </div>
        </div>
      </div>
    </VonDialog>
    <VonDrawer @handleClose="download_handleClose" drawerTitle="详情" :showFooter="false" :form-mode="false"
      :visible="isShow_Drawer_download">
      <div slot="content">
        <div class="whiteLine"></div>
        <div class="tableItem" v-for="(item, index) in ExportList" :key="index">
          <div class="tableItemLeft">
            <div class="workStationName">{{ item.station }}</div>
            <div class="workStationName2">{{ item.stationName }}</div>
            <div class="workStationName3">( {{ item.status }} )</div>
            <div class="smallWhiteLine"></div>
          </div>
          <div class="tableItemRight">
            <div class="container">
              <div class="box">
                <div class="tableItemRightTop tableItemRightItem">
                  <ul style="height: 36px; line-height: 36px">
                    <li v-for="(item_child, index_child) in item.list" style="font-size: 14px" :key="index_child">
                      <a href="#" @click="clickIntoTestResult(item_child.name)" style="color: #9ebadc" v-if="
                        item_child.name == '耐压测试' ||
                        item_child.name == '绝缘测试' ||
                        item_child.name == '压降测试' ||
                        item_child.name == '导通测试' ||
                        item_child.name == 'CAN电流测试' ||
                        item_child.name == '粘连测试' ||
                        item_child.name == '霍尔电流测试' ||
                        item_child.name == '电容测试' ||
                        item_child.name == '电阻测试'
                      ">{{ item_child.name }}</a>
                      <span v-else>{{ item_child.name }}</span>
                    </li>
                  </ul>
                </div>
                <div class="tableItemRightBottom tableItemRightItem">
                  <ul>
                    <li v-for="(item_child, index_child) in item.list" style="font-size: 14px" :key="index_child">
                      {{ formatLineFeed(item_child.value) }}
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </VonDrawer>
    <VonDialog :is-show-footer="false" :isShow_Popup="isShow_Popup_testResult" :isShowCancelButton="false"
      successText="确定" cancelText="" :title="cur_test_result_title" :isHasCloseBtu="true"
      @cancelResult="cancelResult_testResult">
      <div slot="content">
        <VonTable isHasPoint :column="cur_Column" :tableData="cur_test_result_list"></VonTable>
      </div>
    </VonDialog>
  </div>
</template>
<script>
import {
  deleteProductOrder,
  hangupProductOrder,
  getExportListApi,
  getProductOrderPageList,
  getSubTableContentApi,
  postExportListApi,
} from "../../api/workStation/mainControl";
import { closeLoading, openLoading } from "../../common/prompt";
import moment from "moment";

export default {
  name: "DataManage",
  data() {
    return {
      searchButtonFlag: false,
      selectType: "",
      createDate: [new Date().getTime() - 3600 * 1000 * 24 * 30, new Date()],
      searchCondition_Start: "",
      searchCondition_End: "",
      searchItem: [
        { name: "工序", id: "workStationId" },
        { name: "物料码", id: "material" },
        { name: "临时码", id: "tmpBarCode" },
        { name: "操作员", id: "worker" },
        { name: "日期区间", id: "dateRange" },
        { name: "临时码区间", id: "tmpBarCodeRange" },
        { name: "成品码区间", id: "productBarCodeRange" },
      ],
      cur_Column: [
        {
          prop: "stepNumber",
          label: "",
          align: "center",
        },
        {
          prop: "resultValue",
          label: "结果值",
          align: "center",
        },
        {
          prop: "isResultPass",
          label: "判定结果",
          align: "center",
        },
      ],
      cur_test_result_list: [],
      cur_test_result_title: "",
      isShow_Popup_testResult: false,
      isTableRadio: 0,
      isShow_Drawer_download: false,
      isShow_Popup_Bad: false,
      isShow_Popup_tightComplete: false,
      column: [
        {
          align: "center",
          label: "总条形码",
          prop: "productBarCode",
        },
        {
          align: "center",
          label: "临时条形码",
          prop: "tmpBarCode",
        },
        {
          align: "center",
          label: "状态",
          prop: "status",
        },
      ],
      searchCondition: "",
      tableData: [],
      pageIndex: 1,
      pageSize: 20,
      ExportList: [],
      multi_ExportList: [],
      handleList: [],
      TitleId: "",
      totalCount: 0,
    };
  },
  mounted() {
    this.getDataList();
  },
  methods: {
    changeSearchType() {
      if (this.selectType == "" || this.selectType == null) {
        this.searchButtonFlag = false;
      }
      else {
        this.searchButtonFlag = true;
      }
    },
    formatLineFeed(value) {
      if (value.indexOf(",") > -1) {
        return value.replace(/,/g, "\n");
      } else {
        return value;
      }
    },
    clickIntoTestResult(value) {
      this.cur_test_result_title = value;
      this.isShow_Popup_testResult = true;
      let StationName;
      let StepType;
      switch (value) {
        case "耐压测试":
          StationName = "station1";
          StepType = "NY";
          break;
        case "绝缘测试":
          StationName = "station1";
          StepType = "JY";
          break;
        case "压降测试":
          StationName = "station2";
          StepType = "YJ";
          break;
        case "导通测试":
          StationName = "station2";
          StepType = "DT";
          break;
        case "CAN电流测试":
          StationName = "station2";
          StepType = "CAN";
          break;
        case "粘连测试":
          StationName = "station2";
          StepType = "FN";
          break;
        case "霍尔电流测试":
          StationName = "station2";
          StepType = "HE";
          break;
        case "电容测试":
          StationName = "station2";
          StepType = "DR";
          break;
        case "电阻测试":
          StationName = "station2";
          StepType = "DZ";
          break;
      }
      let params = {
        TitleId: this.TitleId,
        StationName, //18的传station1,19的传station2
        StepType,
      };
      this.getSubTableContent(params);
    },
    cancelResult_testResult() {
      this.isShow_Popup_testResult = false;
    },
    handleCurrentChange(value) {
      this.pageIndex = value;
      this.getDataList();
    },
    handleSizeChange(value) {
      this.pageSize = value;
      this.getDataList();
    },
    selectionChange(list) {
      this.handleList = list.map((item) => {
        return item.id;
      });
    },
    commitResult_Bad() {
      this.isShow_Popup_Bad = false;
    },
    cancelResult_Bad() {
      this.isShow_Popup_Bad = false;
    },
    cancelResult_tightComplete() {
      this.isShow_Popup_tightComplete = false;
    },
    commitResult_tightComplete() {
      this.isShow_Popup_tightComplete = false;
    },
    download_handleClose() {
      this.isShow_Drawer_download = false;
    },
    getDrawerData(status, titleId) {
      this.TitleId = titleId;
      getExportListApi({ titleId }).then((res) => {
        if (res.status === 200) {
          let tempList = res.data;
          tempList.forEach((item) => {
            let list = [];
            if (item.data) {
              for (let [key, value] of Object.entries(item.data)) {
                let obj = {};
                obj.name = key;
                obj.value = value;
                list.push(obj);
              }
            }
            item.list = list;
          });
          this.ExportList = tempList;
        } else {
          this.$message.error("获取数据失败");
        }
        this.isShow_Drawer_download = status;
      });
    },
    searchDataList() {
      this.pageIndex = 1;
      this.getDataList();
    },
    getDataList() {
      var filter = "",
        startFilter = "",
        endFilter = "";
      if (this.selectType == "dateRange") {
        if (this.createDate.length > 0) {
          startFilter = moment(this.createDate[0]).format("YYYY-MM-DD");
          endFilter = moment(this.createDate[1]).format("YYYY-MM-DD");
        }
      }
      else if (this.selectType == "workStationId" || this.selectType == "material" || this.selectType == "tmpBarCode" || this.selectType == "worker") {
        filter = this.searchCondition;
      }
      else if (this.selectType == "tmpBarCodeRange" || this.selectType == "productBarCodeRange") {
        startFilter = this.searchCondition_Start;
        endFilter = this.searchCondition_End;
      }
      const params = {
        selectType: this.selectType,
        filter: filter,
        startFilter: startFilter,
        endFilter: endFilter,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
      };
      openLoading();
      getProductOrderPageList(params).then((res) => {
        closeLoading();
        if (res.status == 200) {
          this.tableData = res.data.items;
          this.totalCount = res.data.totalCount;
        } else {
          this.$message.error(res.error.message);
        }
      });
    },
    del(row) {
      this.$confirm("是否确认操作？").then(() => {
        let data = { id: row.id };
        deleteProductOrder(data).then((res) => {
          this.isShow_Popup = false;
          if (res.status == 200 || res.status == 204) {
            this.$message.success("删除成功");
            this.getDataList();
          } else {
            this.$message.error("删除失败");
          }
        });
      });
    },
    hangup(row) {
      this.$confirm("是否确认操作？").then(() => {
        let data = { id: row.id };

        const exportdata = {
          titleId: [row.id],
        };
        openLoading();
        postExportListApi(exportdata).then((res) => {
          //fileName:下载的文件名
          var fileName = decodeURIComponent(
            res.headers["content-disposition"].split("=")[1]
          );
          let blob = new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
          });

          // 针对ie浏览器
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName);
          } else {
            //非ie浏览器
            var downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //常见下载的链接
            downloadElement.href = href;
            downloadElement.download = fileName; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href); //释放blob对象
          }
        });

        hangupProductOrder(data).then((res) => {
          this.isShow_Popup = false;
          if (res.status == 200 || res.status == 204) {
            this.$message.success("挂起成功");
            this.getDataList();
          } else {
            this.$message.error("挂起失败");
          }
        });
      });
    },
    getSubTableContent(params) {
      getSubTableContentApi(params).then((res) => {
        if (res.status === 200) {
          let list = res.data;
          list.forEach((item) => {
            if (item.isResultPass) {
              item.isResultPass = "PASS";
            } else {
              item.isResultPass = "STOP";
            }
          });
          this.cur_test_result_list = res.data;
        } else {
          this.$message.error(res.data.message || "获取数据失败");
        }
      });
    },
    exportData() {
      const data = {
        titleId: [...this.handleList],
      };
      openLoading();
      postExportListApi(data).then((res) => {
        //fileName:下载的文件名
        var fileName = decodeURIComponent(
          res.headers["content-disposition"].split("=")[1]
        );
        let blob = new Blob([res.data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
        });

        // 针对ie浏览器
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          //非ie浏览器
          var downloadElement = document.createElement("a");
          var href = window.URL.createObjectURL(blob); //常见下载的链接
          downloadElement.href = href;
          downloadElement.download = fileName; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放blob对象
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "../../style/mainControl";

.rangeTag {
  color: white;
  width: 40px;
}

.range-header {
  margin: 10px 10px;
  width: 100%;

  .range {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 370px;
  }
}

.warningBox {
  width: 560px;
  height: 275px;
  background: rgba(152, 166, 197, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;

  .title_warning {
    height: 49px;
    font-size: 50px;
    margin-top: 40px;
    font-family: Source Han Sans CN;
    font-weight: bold;
    color: #b9c5dd;
    line-height: 60px;
  }
}

.whiteLine {
  width: 100%;
  height: 1px;
  margin: 10px 0;
  background: #ffffff;
  border-radius: 1px;
}

.allCheckedBox {
  display: flex;
  justify-content: space-between;
  padding: 0 4px;
}

.tableItem {
  margin: 10px 0;
  padding: 4px 10px;
  height: 120px;
  background: rgba(152, 166, 197, 0.2);
  border-radius: 10px;
  display: flex;
  overflow-x: scroll;

  .tableItemLeft {
    height: 100%;
    width: 220px;
    flex: 0 0 220px;
    display: flex;
    align-items: center;
    justify-content: space-evenly;

    .workStationName {
      width: 44px;
      height: 44px;
      background: #336cb5;
      border: 1px solid #336cb5;
      border-radius: 2px;
      line-height: 44px;
      text-align: center;
    }

    .workStationName2 {
      font-size: 18px;
      font-weight: bold;
      color: #ffffff;
    }

    .workStationName3 {
      font-size: 14px;
      color: #ffffff;
    }

    .smallWhiteLine {
      height: 60px;
      width: 1px;
      background: white;
    }
  }

  .tableItemRight {
    padding: 10px 0 0 0;
    flex: 1;

    .container {
      .box {
        .tableItemRightItem {
          ul {
            width: 100%;
            display: flex;
            justify-content: space-evenly;
            height: 40px;
            line-height: 40px;

            li {
              padding-top: 4px;
              text-align: center;
              list-style: none;
              width: 123px;
              line-height: 1.2;
            }
          }
        }

        .tableItemRightTop {}

        .tableItemRightBottom {}
      }
    }
  }
}
</style>
